﻿using Abp.Dependency;
using Abp.Threading;
using AbpProjectTemplate.Components.Notifications.SMS;
using System.ComponentModel.DataAnnotations;
using System;

namespace AbpProjectTemplate.Utilities.Validation
{
    /// <summary>
    /// 手机验证码验证特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class MobileCodeAttribute : ValidationAttribute
    {
        private readonly ISmsSender _smsSender;
        public string MobileProperty { get; private set; }
        public MobileCodeAttribute(string mobileProperty)
        {
            this.MobileProperty = mobileProperty;
            this._smsSender = IocManager.Instance.Resolve<ISmsSender>();
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
                return new ValidationResult("请输入手机验证码。");
            var otherPropertyInfo = validationContext.ObjectType.GetProperty(this.MobileProperty);
            if (otherPropertyInfo == null)
            {
                return new ValidationResult("未指定或者错误的手机号码字段指定。");
            }
            var mobile = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (mobile == null)
                return new ValidationResult("未指定或者错误的手机号码字段指定。");
            var strMobile = mobile.ToString();

            if (!AsyncHelper.RunSync(() => this._smsSender.ValidateMobileCodeAsync(strMobile, value.ToString())))
                return new ValidationResult("手机验证码输入错误或已过期。");
            return null;
        }

        //public override bool IsValid(object value)
        //{
        //    var request = HttpContext.Current.Request;
        //    var code = request["luotest_response"];
        //    if (code.IsNullOrWhiteSpace())
        //    {
        //        this.ErrorMessage = VerifyCodeConfig.NullErrorMessage;
        //        return false;
        //    }

        //    var b = VerifyCodeHelper.Verify(code);
        //    if (!b)
        //        this.ErrorMessage = VerifyCodeConfig.ErrorMessage;
        //    this.RequiresValidationContext.
        //    return b;
        //}
    }
}

